package FilePanel;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Observable;

import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;

/**
 * @author      Erwan Osouf, Lucas Ennouchi
 * @version     1.0                                
 * @since       29/01/2012
 */

public class FilePanelModel extends Observable implements ListModel,Data{

	private File root;
	ArrayList<File> files;
	private int[] selectedIndex;
	ArrayList<ListDataListener> listeners;
	public FilePanelModel(File root) {
		super();
		this.setRoot(root);
		this.files = new ArrayList<File>(Arrays.asList(root.listFiles()));
		this.selectedIndex = null;
		this.listeners = new ArrayList<ListDataListener>();
	}
	
	public File getRoot() {
		return root;
	}

	public void setRoot(File root) {
		this.root = root;
		File[] tabFiles = root.listFiles();
		this.files = new ArrayList<File>();
		for(File f : tabFiles){
			files.add(f);
		}
		this.setChanged();
		this.notifyObservers();		
		this.selectedIndex = null;
	}

	public ArrayList<File> getFiles() {
		return files;
	}

	public int[] getSelectedIndexes() {
		return selectedIndex;
	}

	public void setSelectedIndex(int[] selectedIndex) {
		this.selectedIndex = selectedIndex;
	}

	@Override
	public void addListDataListener(ListDataListener arg0) {
		this.listeners.add(arg0);
	}

	@Override
	public Object getElementAt(int arg0) {
		return files.get(arg0);
	}

	@Override
	public int getSize() {
		return files.size();
	}

	

	@Override
	public void removeListDataListener(ListDataListener arg0) {
		this.listeners.remove(arg0);
	}

	@Override
	public ArrayList<File> getSelectedFiles() {
		ArrayList<File> al = new ArrayList<File>();
		int[] indexes = getSelectedIndexes();
		try{
			for(int i=0; i < indexes.length;i++){
				al.add(getFiles().get(indexes[i]));
			}
		}catch(NullPointerException e){
			
		}
		return al;
	}

	@Override
	public boolean isSelected(File f) {
		return getSelectedFiles().contains(f);
	}

	@Override
	public File getFileAt(int i) {
		return getFiles().get(i);
	}

	@Override
	public File getSelectedFileAt(int i) {
		return getSelectedFiles().get(i);
	}
	
	public String toString(){
		String result = "";
		result+= "Root : "+this.getRoot()+"\n";
		result+= "Files : "+files.toString();
		return result;
	}

}
